package com.citcc.api.controller;

import com.citcc.api.config.Authorization;
import com.citcc.api.utils.PaymentServiceUtil;
import com.citcc.business.bean.CdzAccountAmount;
import com.citcc.business.bean.CdzAmountDetail;
import com.citcc.business.bean.CdzAppUser;
import com.citcc.business.bean.dto.PaymentDTO;
import com.citcc.business.bean.vo.PaymentVO;
import com.citcc.business.mapper.CdzAccountAmountMapper;
import com.citcc.business.mapper.CdzAmountDetailMapper;
import com.citcc.business.util.IdGenerator;
import com.citcc.common.msg.Response;
import com.citcc.common.utils.ResponseUtil;
import com.citcc.common.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;

/**
 * Created by czh on 2019/5/21 0021 14:31
 */
@Api(value = "充值提现", tags = "我的钱包")
@RestController
@RequestMapping("/payment")
public class PaymentController {

    @Autowired
    private PaymentServiceUtil paymentService;
    @Autowired
    private CdzAmountDetailMapper amountDetailMapper;
    @Autowired
    private CdzAccountAmountMapper accountAmountMapper;

    /**
     * 充值
     *
     * @param user
     * @param tradeType
     * @param amount
     * @return
     */
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tradeType", value = "支付方式 微信APP支付：wx-app-pay；支付宝APP支付：zfb-app-pay", required = true),
            @ApiImplicitParam(name = "amount", value = "充值金额", required = true)
    })
    @PostMapping("/v1/recharge")
    @ApiOperation(value = "充值", notes = "需要在header中加入Authorization。")
    @Transactional(rollbackFor = Exception.class)
    public Response<Object> recharge(@ApiIgnore @Authorization CdzAppUser user,
                                     @RequestParam("tradeType") String tradeType,
                                     @RequestParam("amount") String amount,
                                     HttpServletRequest request) {

        if (StringUtils.isBlank(tradeType) || StringUtils.isBlank(amount))
            return ResponseUtil.fail(null, "充值金额或支付方式不能为空");

        // 用户ID
        String userId = user.getId();
        // 商户订单号（余额明细表中对应的主键ID，用于回调更改支付状态）
        String outTradeNo = IdGenerator.generateId();

        PaymentVO paymentVO = new PaymentVO();
        paymentVO.setPayMoney(new BigDecimal(amount));
        paymentVO.setTradeType(tradeType);
        paymentVO.setOutTradeNo(outTradeNo);
        paymentVO.setUserId(userId);
        paymentVO.setDescription("用户充值操作，金额（元）：" + paymentVO.getPayMoney());
        PaymentDTO paymentDTO = paymentService.recharge(request, paymentVO);
        if (paymentDTO.getPayState()) {
            // 获取总金额
            CdzAccountAmount cdzAccountAmount = accountAmountMapper.selectByUserId(userId);
            // 创建充值记录
            CdzAmountDetail cdzAmountDetail = new CdzAmountDetail();
            cdzAmountDetail.setId(outTradeNo);
            cdzAmountDetail.setUserId(userId);
            cdzAmountDetail.setType("1");
            if (cdzAccountAmount == null || cdzAccountAmount.getTotalAmount() == null) {
                cdzAmountDetail.setBeforeAmount(new BigDecimal("0.00"));
            } else {
                cdzAmountDetail.setBeforeAmount(cdzAccountAmount.getTotalAmount());
            }
            cdzAmountDetail.setAmount(paymentVO.getPayMoney());
            cdzAmountDetail.setAfterAmount(cdzAmountDetail.getBeforeAmount().add(cdzAmountDetail.getAmount()));
            String payType = null;
            switch (tradeType) {
                case "wx-app-pay":
                    payType = "1";
                    break;
                case "zfb-app-pay":
                    payType = "0";
                    break;
                default:
            }
            cdzAmountDetail.setPayType(payType);
            cdzAmountDetail.setPayState("1");
            cdzAmountDetail.setCreateTime(new Date());
            cdzAmountDetail.setCreateBy(userId);
            cdzAmountDetail.setUpdateTime(cdzAmountDetail.getCreateTime());
            cdzAmountDetail.setUpdateBy(userId);
            cdzAmountDetail.setDelFlag("0");
            amountDetailMapper.insertSelective(cdzAmountDetail);
            return ResponseUtil.success(paymentDTO.getResult());
        }
        return ResponseUtil.fail(null);
    }

    /**
     * 提现
     *
     * @param user
     * @param tradeType
     * @param amount
     * @param request
     * @return
     */
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tradeType", value = "提现方式 微信APP支付：wx-app-pay；支付宝APP支付：zfb-app-pay", required = true),
            @ApiImplicitParam(name = "amount", value = "提现金额", required = true)
    })
    @PostMapping("/v1/presentation")
    @ApiOperation(value = "提现", notes = "需要在header中加入Authorization。")
    @Transactional(rollbackFor = Exception.class)
    public Response<Object> presentation(@ApiIgnore @Authorization CdzAppUser user,
                                         @RequestParam("tradeType") String tradeType,
                                         @RequestParam("amount") String amount,
                                         HttpServletRequest request) {
        return ResponseUtil.fail(null, "本版本暂不支持账户余额提现。如需提现，请联系 15093133375");
    }
}